package com.boot.security.server.agency.Utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.boot.security.server.agency.model.vo.AgencyRecordVo;
import io.micrometer.core.instrument.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author king
 */
@Slf4j
public class InterfaceUtils {
    public static void exchangeRestResponse (AgencyRecordVo response, HttpServletRequest request, HttpServletResponse httpResp) {
        try {
            String result = JSON.toJSONString(response, new SerializerFeature[] {SerializerFeature.WriteMapNullValue});
            log.info(" 请求返回数据:" + result);
            httpResp.setContentType("text/json;charset=UTF-8");
            httpResp.setCharacterEncoding("UTF-8");
            PrintWriter out = httpResp.getWriter();
            out.write(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查Cookie获得 SSO Token
     * key=iPlanetDirectoryPro
     * @param request
     * @return token
     */
    public static String checkCookie (HttpServletRequest request) {
        Cookie cookies[] = request.getCookies();
        String token = null;
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals("iPlanetDirectoryPro")) {
                    token = cookies[i].getValue();
                    break;
                }
            }
        }
        return token;
    }

    /**
     * 根据SSO Token 获得用户工号
     * @param token
     * @return 工号
     */
    public static String SSOTokenLoginGetCode (String token) {
        String userCode = null;
        URLConnection uc = null;
        try {
            URL url = new URL("http://portal.oa.unionpay.com/ssotoken/checktokencode");
            uc = url.openConnection();
            uc.setDoOutput(true);
            uc.setDoInput(true);
            uc.setUseCaches(false);

            ObjectOutputStream objectstream = new ObjectOutputStream(uc.getOutputStream());
            objectstream.writeObject(token);
            objectstream.flush();
            objectstream.close();

            InputStream in = uc.getInputStream();
            ObjectInputStream objectin = new ObjectInputStream(in);
            Object myobject = objectin.readObject();
            userCode = (String) myobject;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return userCode;
    }
}
